package 牛客面试;

import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import 二叉树.TreeNode;

import java.util.ArrayDeque;
import java.util.Deque;

public class 序列化和反序列化二叉树 {

    private String Serialize(TreeNode root) {
        Deque<TreeNode> deque=new ArrayDeque<>();
        deque.addFirst(root);
        StringBuilder sb=new StringBuilder();
        while(!deque.isEmpty()){
            TreeNode node=deque.removeFirst();
            sb.append(node.val);
            if(node.left!=null) {
                deque.addLast(node.left);
            }
            if(node.right!=null) {
                deque.addLast(node.right);
            }
        }
        return sb.toString();
    }
    private TreeNode Deserialize(String str) {
        //层序遍历出的字符串
        char[] arr=str.toCharArray();
        Deque<TreeNode> deque=new ArrayDeque<>();
        int index=0;
        TreeNode node=new TreeNode(arr[index++]-'0');
        deque.addLast(node);
        while(!deque.isEmpty()){
            TreeNode treeNode=deque.removeFirst();
            if(index<arr.length) {
                treeNode.left = new TreeNode(arr[index++] - '0');
                deque.addLast(treeNode.left);
            }

            if(index<arr.length) {
                treeNode.right = new TreeNode(arr[index++] - '0');
                deque.addLast(treeNode.right);
            }
        }
        return node;
    }

    public static void main(String[] args) {
        TreeNode node = TreeNode.getNodeByArr(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        序列化和反序列化二叉树 n=new 序列化和反序列化二叉树();
        String str = n.Serialize(node);
        TreeNode treeNode = n.Deserialize(str);
        System.out.println(str);
        System.out.println(treeNode);
    }

}
